package com.hzqy.service.ift;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import java.util.regex.Pattern;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.ConstantUtils;
import com.hzqy.commons.utils.YXTUtil;
import com.hzqy.persistence.dao.itf.LoginDao;
import com.hzqy.service.core.GenericServiceBean;
import com.hzqy.web.vo.CmContentVo;
import com.hzqy.web.vo.PmsAttributeVo;
import com.hzqy.web.vo.PmsOrgVo;
import com.hzqy.web.vo.PmsResourceVo;
import com.hzqy.web.vo.PmsUserVo;

@Service
public class LoginServiceBean extends GenericServiceBean<CmContentVo, LoginDao, Integer>{

	private static final long serialVersionUID = 1L;
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	private static final long TIME_INTERVAL = 1 * 24 * 60 * 60 * 1000;//一天
	private static final Pattern timestampPattern = Pattern.compile("[0-9]{13}");
	private static final Map<String, String> secretMap = new HashMap<String, String>();//secretcode
	private static final Map<String, String> errorUrlMap = new HashMap<String, String>();//登录失效跳转地址
	private static final String CHARSET = "UTF-8";
	
	static{
		secretMap.put("yxt", "XHGsOv54lPPfPgLTfQuqsB3zyQXAumNw");
		errorUrlMap.put("yxt", "http://zhkt.114school.com:82/myapp/p/msg.jsp?error=");
	}
	
	@Resource
	private LoginDao loginDao;

	@Override
	public LoginDao getEntityDao() {
		return loginDao;
	}
	
	private static final boolean isEmpty(String s){
		if(s == null)return true;
		if("".equals(s.trim()))return true;
		if("null".equals(s.trim()))return true;
		return false;
	}
	
	private Map<String, Object> checkLoginParams(Map<String, Object> params, String key){
		Map<String, Object> result = new HashMap<String, Object>();
		
		String app = String.valueOf(params.get("app"));
		String username = String.valueOf(params.get("username"));
		String pwd = String.valueOf(params.get("pwd"));
		String realname = String.valueOf(params.get("realname"));
		String timestampStr = String.valueOf(params.get("timestamp"));
		String orgname = String.valueOf(params.get("orgname"));
		String orgid = String.valueOf(params.get("orgid"));
		String secret = String.valueOf(params.remove("secret"));
		
		//parameter empty check
		if(isEmpty(app) || isEmpty(username) 
				|| isEmpty(pwd) || isEmpty(realname) 
				|| isEmpty(timestampStr) || isEmpty(orgname) 
				|| isEmpty(orgid) || isEmpty(secret)){
			result.put("checksuccess", false);
			result.put("checkcode", "01");
			result.put("checkmsg", "参数缺失");
			return result;
		}
		
		//timestamp check
		try {
			if(timestampPattern.matcher(timestampStr).matches()){
				long timestamp = Long.parseLong(timestampStr);
				if(System.currentTimeMillis() - timestamp > TIME_INTERVAL){
					result.put("checksuccess", false);
					result.put("checkcode", "02");
					result.put("checkmsg", "登录过时");
					return result;
				}
			}else{
				result.put("checksuccess", false);
				result.put("checkcode", "02");
				result.put("checkmsg", "时间格式错误");
				return result;
			}
		} catch (Exception e) {
			result.put("checksuccess", false);
			result.put("checkcode", "02");
			result.put("checkmsg", "时间参数不合法");
			return result;
		}
		
		//app exist check
		if(secretMap.get(app) == null){
			result.put("checksuccess", false);
			result.put("checkcode", "03");
			result.put("checkmsg", "app不存在");
			return result;
		}
		
		//secret check
		String mySecret = YXTUtil.sign(params, key);
		if(!secret.equals(mySecret)){
			result.put("checksuccess", false);
			result.put("checkcode", "05");
			result.put("checkmsg", "secret验证失败");
			return result;
		}
		
		result.put("checksuccess", true);
		return result;
	}
	
	public Map<String, Object> login(Map<String, String[]> params){
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> paramsMap = new TreeMap<String, Object>();
		
		try {
			Iterator<Entry<String, String[]>> it = params.entrySet().iterator();
			while(it.hasNext()){
				Entry<String, String[]> entry = it.next();
				paramsMap.put(entry.getKey(), entry.getValue()[0]);
			}
			String secretcode = secretMap.get(paramsMap.get("app"));
			Map<String, Object> checkResult = checkLoginParams(paramsMap, secretcode);
			if((Boolean)checkResult.get("checksuccess")){
				PmsOrgVo org = loginDao.selectOrgByName(String.valueOf(paramsMap.get("orgname")));
				if(org != null){
					PmsUserVo user = loginDao.selectClickLoginUser(org.getF_po_id(), "com.hzkd.clicklogin.user.");
					if(user != null){
						//登录
						PmsUserVo puv = new PmsUserVo();
						puv.setF_pu_name(user.getF_pu_name());
						puv.setF_pu_pwd(user.getF_pu_pwd());
						PmsUserVo userVo = loginDao.findUser(puv);
						if(userVo != null){
							List<PmsAttributeVo> pavList= loginDao.selectUserAttributeList(userVo.getRoleIds());
							List<PmsResourceVo> resourceList = loginDao.selectUserResourceList(userVo.getRoleIds());
							resultMap.put(ConstantUtils.SESSION_ATTRIBUTE, pavList);
							resultMap.put(ConstantUtils.SESSION_RESOURCE, resourceList);
							resultMap.put(ConstantUtils.SESSION_USER, userVo);
							
							//动态切换至对应的组织
							userVo.setF_pu_name(String.valueOf(paramsMap.get("realname")));
							userVo.setOrgId(org.getF_po_id());
							userVo.setParentOrgId(org.getF_po_parentId());
							resultMap.put("success", true);
						}else{
							resultMap.put("success", false);
							resultMap.put("errorcode", "02");
							resultMap.put("errormsg", "用户名或密码错误");
						}
					}else{
						resultMap.put("success", false);
						resultMap.put("errorcode", "08");
						resultMap.put("errormsg", "组织无一点登录账号");
					}
				}else{
					resultMap.put("success", false);
					resultMap.put("errorcode", "04");
					resultMap.put("errormsg", "组织未开户");
				}
			}else{
				resultMap.put("success", false);
				resultMap.put("errorcode", checkResult.get("checkcode"));
				resultMap.put("errormsg", checkResult.get("checkmsg"));
			}
		} catch (Exception e) {
			LOG.error("", e);
			resultMap.put("success", false);
			resultMap.put("errorcode", "99");
			//resultMap.put("errormsg", e.getMessage());
		}
		
		
		//如果失败，生成回跳路径
		if(!(Boolean)resultMap.get("success")){
			try {
				String errorUrl = errorUrlMap.get(paramsMap.get("app"));
				if(isEmpty(errorUrl)){
					resultMap.put("exist_errorurl", false);
				}else{
					resultMap.put("exist_errorurl", true);
					Map<String, String> result = new HashMap<String, String>();
					result.put("errorcode", String.valueOf(resultMap.get("errorcode")));
					result.put("errormsg", String.valueOf(resultMap.get("errormsg")));
					errorUrl += URLEncoder.encode(JSONObject.toJSONString(result), CHARSET);
					resultMap.put("errorurl", errorUrl);
				}
			} catch (UnsupportedEncodingException e) {
				LOG.error("", e);
			}
		}
		
		return resultMap;
	}
	
	
}
